<template>
  <div class="container">
    <VerticalLayout :isSearchCollapsed="isSearchCollapsed">
      <template #filters>
        <!-- 发货部 -->
        <FilterForm role="shipping" @change="filterChange" />
      </template>
      <!-- 插入搜索组件 -->
      <template #search>
        <el-space alignment="flex-start">
          <el-switch
            v-model="isSearchCollapsed"
            active-color="#13ce66"
            inactive-color="#ff4949"
            inline-prompt
            active-text="展开"
            inactive-text="收起"
          />

          <DynamicQueryForm
            :show-match-range="true"
            :extra-fields="extraField"
            :columns-values="columnsValues"
            @submit="onSubmit"
          />
        </el-space>
      </template>

      <!-- 插入表格组件 -->
      <template #table>
        <CustomTable
          ref="customTableRef"
          :actions="listRepeatPurchaseOrder"
          :columns="columns"
          show-selection
          show-pagination
          @selection-change="onSelectionChange"
        >
          <!-- 左边功能 -->
          <template #action-left>
            <el-button type="primary" :icon="Plus" @click="onAdd('add')">创建复购单</el-button>
            <el-button type="primary" :icon="Plus" @click="onMultiPackage"
              >创建多包裹复购单</el-button
            >
            <el-button type="primary" :icon="Van" @click="onReturnOrder()">新增退货单</el-button>

            <el-button type="primary" :icon="Van" @click="onReplenishOrder()">新增补货单</el-button>

            <el-button type="primary" :icon="Plus" @click="onAdd('superaddition')"
              >追加（平台转定金/复购）</el-button
            >
          </template>

          <!-- 右边功能 -->
          <template #action-right>
            <el-button :icon="Refresh" circle @click="customTableRef?.refresh" />
          </template>

          <template #table-top v-if="selections.length > 0">
            <el-alert :closable="false">
              <template #title>
                {{ `您已选择${selections.length}条订单，是否需要` }}
                <el-button class="alertFpBtn" type="primary" size="small" text @click="onBatchPrint"
                  >批量打印</el-button
                >
              </template>
            </el-alert>
          </template>

          <template #orderSlot="{ row }">
            <RowSlots slotName="repeatOrderSlot" :row="row" />
          </template>
          <!-- 收货人信息 -->
          <template #logisticsSlot="{ row }">
            <RowSlots slotName="repeatLogisticsSlot" :row="row" @payHistory="payHistory" />
          </template>

          <!-- 订单类型 -->
          <template #orderTypeSlot="{ row }">
            <RowSlots slotName="orderTypeSlot" :row="row" />
          </template>

          <!-- 包裹信息 -->
          <template #isMultiPackageSlot="{ row }">
            <RowSlots slotName="isMultiPackageSlot" :row="row" />
          </template>

          <!-- 业务员信息 -->
          <template #salesmanSlot="{ row }">
            <RowSlots slotName="salesmanSlot" :row="row" />
          </template>

          <!-- 类别 -->
          <template #categorySlot="{ row }">
            <RowSlots slotName="categorySlot" :row="row" />
          </template>
          <!-- 商品数量 -->
          <template #dosageSlot="{ row }">
            <RowSlots slotName="repeatDosageSlot" :goodsTypes="goodsTypes" :row="row" />
          </template>

          <!-- 物流信息 -->
          <template #logisticsStatusSlot="{ row }">
            <RowSlots slotName="logisticsStatusSlot" :row="row" />
          </template>

          <!-- 下单/签收时间 -->
          <template #orderTimerSlot="{ row }">
            <RowSlots slotName="orderTimerSlot" :row="row" />
          </template>

          <template #wechatSlot="{ row }">
            <RowSlots slotName="wechatSlot" :row="row" />
          </template>

          <!-- 操作 -->
          <template #operationSlot="{ row }">
            <!-- 已经取消的订单 不能再操作 -->
            <!-- row.orderStatus == 130 订单已取消 不能再操作 -->
            <el-dropdown
              v-if="!row.isChildren && ![130].includes(row.orderStatus)"
              trigger="click"
              placement="bottom-end"
              @command="(cmd: any) => handleCommand(cmd, row)"
            >
              <el-button type="primary" size="small" text>
                <el-icon><Setting /></el-icon>
                <span>设置</span>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- 多包裹订单不允许编辑 -->
                  <el-dropdown-item v-if="!row.isMultiPackage" :icon="Edit" command="edit"
                    >编辑</el-dropdown-item
                  >
                  <!-- 分配业务员 -->
                  <!-- <el-dropdown-item :icon="Finished" command="allocation">
                    {{ row.salesmanId ? '重新分配' : '分配' }}
                  </el-dropdown-item> -->

                  <!-- 根据是否发货显示不同项 -->
                  <template v-if="!row.logisticsNo">
                    <el-dropdown-item :icon="Printer" command="print" type="primary">
                      打印发货
                    </el-dropdown-item>
                    <el-dropdown-item :icon="RemoveFilled" command="cancel" :danger="true">
                      取消发货
                    </el-dropdown-item>
                  </template>
                  <!-- 订单已发货 但是 未被签收 和 完成的 -->
                  <el-dropdown-item
                    v-else-if="![190, 200].includes(row.orderStatus)"
                    :icon="Van"
                    command="intercept"
                    :danger="true"
                  >
                    物流拦截
                  </el-dropdown-item>
                  <!-- 已发货的订单 不能再删除 -->
                  <el-dropdown-item
                    v-if="!row.logisticsNo"
                    :icon="DeleteFilled"
                    command="del"
                    :danger="true"
                  >
                    删除
                  </el-dropdown-item>
                  <!-- 
                    已经发货未签收 的才能补单和退货 
                  -->
                  <template v-if="row.logisticsNo && row.orderStatus == 2">
                    <el-dropdown-item :icon="Van" command="return" :danger="true">
                      退货
                    </el-dropdown-item>

                    <el-dropdown-item :icon="Van" command="replenish" type="primary">
                      补单
                    </el-dropdown-item>
                  </template>

                  <!-- 修改代付（仅代付订单显示 支付方式 4） -->
                  <!-- <el-dropdown-item
                    v-if="row.paymentMethod == 4"
                    :icon="Edit"
                    command="modifyPayment"
                    type="primary"
                  >
                    修改代付
                  </el-dropdown-item> -->
                  <el-dropdown-item
                    v-if="+row.topStatus === 2"
                    :icon="Top"
                    command="top"
                    type="primary"
                  >
                    置顶
                  </el-dropdown-item>
                  <el-dropdown-item v-else :icon="SemiSelect" command="cancelTop" :danger="true">
                    取消置顶
                  </el-dropdown-item>

                  <!-- 完成 -->
                  <el-dropdown-item :icon="Check" command="complete" type="primary">
                    订单完成
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 子单只有 取消发货和拦截-->
            <el-dropdown
              trigger="click"
              placement="bottom-end"
              @command="(cmd: any) => handleCommand(cmd, row)"
              v-if="row.isChildren && ![130].includes(row.orderStatus)"
            >
              <el-button type="primary" size="small" text>
                <el-icon><Setting /></el-icon>
                <span>设置</span>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- 根据是否发货显示不同项 -->
                  <template v-if="!row.logisticsNo">
                    <el-dropdown-item :icon="RemoveFilled" command="cancel" :danger="true">
                      取消发货
                    </el-dropdown-item>
                  </template>
                  <!-- 订单已发货 但是 未被签收 和 完成的 -->
                  <el-dropdown-item
                    v-else-if="![190, 200].includes(row.orderStatus)"
                    :icon="Van"
                    command="intercept"
                    :danger="true"
                  >
                    物流拦截
                  </el-dropdown-item>

                  <!-- 完成 -->
                  <el-dropdown-item :icon="Check" command="complete" type="primary">
                    订单完成
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </CustomTable>
      </template>
    </VerticalLayout>
    <!-- 筛选弹窗 -->
    <FilterTable ref="filterTableRef" />
    <!-- 跟进详情 -->
    <CustomerFollowUp ref="customerFollowUpRef" @ok="customTableRef?.refresh" />

    <!-- 批量下发 -->
    <BatchAllocations
      :logisticsCompany="logisticsCompany"
      :users="users"
      :logisticsTypeOptions="logisticsTypeOptions"
      :sysSelfFulfillmentOgistics="sysSelfFulfillmentOgistics"
      @ok="customTableRef?.refresh"
      ref="batchAllocationRef"
    />
    <!-- 用户下单记录 -->
    <CustomerOrderHistory ref="customerOrderHistoryRef" />
    <!-- 创建/追加复购单 -->
    <AddPorder
      :goodsList="goodsList"
      :logisticsCompany="logisticsCompany"
      :payType="payType"
      :orderFrom="orderFrom"
      :goodsTypes="goodsTypes"
      :orderTypeOptions="orderTypeOptions"
      :sysSelfFulfillmentOgistics="sysSelfFulfillmentOgistics"
      :logisticsTypeOptions="logisticsTypeOptions"
      ref="addPorderRef"
      @ok="customTableRef?.refresh"
    />
    <!-- 创建多包裹订单 -->
    <CreateMultiPackageOrder
      :goodsList="goodsList"
      :goodsTypes="goodsTypes"
      :logisticsCompany="logisticsCompany"
      :logisticsTypeOptions="logisticsTypeOptions"
      :sysSelfFulfillmentOgistics="sysSelfFulfillmentOgistics"
      :orderFrom="orderFrom"
      :payType="payType"
      @ok="customTableRef?.refresh"
      ref="createMultiPackageOrderRef"
    />
    <!-- 新增退货单 -->
    <ReturnOrderDialog
      :orderTypeOptions="orderTypeOptions"
      :returnTypeOptions="returnTypeOptions"
      :goodsTypes="goodsTypes"
      ref="returnOrderDialogRef"
    />
    <!-- 新增补货单 -->
    <ReplenishOrderDialog
      :orderTypeOptions="orderTypeOptions"
      :goodsList="goodsList"
      :replenishTypeOptions="replenishTypeOptions"
      :goodsTypes="goodsTypes"
      :sysSelfFulfillmentOgistics="sysSelfFulfillmentOgistics"
      :logisticsCompany="logisticsCompany"
      :payType="payType"
      :logisticsTypeOptions="logisticsTypeOptions"
      @ok="customTableRef?.refresh"
      ref="replenishOrderDialogRef"
    />
    <!-- 修改代付金额 -->
    <ModifyPaymentDialog ref="modifyPaymentDialogRef" />
    <!-- 批量打印 -->
    <BatchPrintDialog :logisticsCompany="logisticsCompany" ref="batchPrintDialogRef" />
    <!-- 单张打印 -->
    <SinglePrintDialog
      :logisticsCompany="logisticsCompany"
      :payType="payType"
      :logisticsTypeOptions="logisticsTypeOptions"
      :sysSelfFulfillmentOgistics="sysSelfFulfillmentOgistics"
      @ok="customTableRef?.refresh"
      ref="singlePrintDialogRef"
    />
  </div>
</template>

<script setup lang="ts">
import {
  Plus,
  Edit,
  Van,
  RemoveFilled,
  DeleteFilled,
  Refresh,
  Top,
  Printer,
  Setting,
  Finished,
  Check,
  SemiSelect
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { columns } from './columns';
import { cloneDeep, isEmpty } from 'lodash';
import { ref, watch } from 'vue';
import { listRepeatPurchaseOrder } from '../../../api/platformOrders/orders/repeatPurchaseOrder';
import { columnsValues, extraField } from './searchOptions';
import { useDict } from '../../../utils/dict';
import { useYw } from '../../../hooks/useYw';
import { useGoods } from '../../../hooks/useGoods';
import { onMounted } from 'vue';
import { useCustomStore } from '../../../store/modules/custom';
import { useLogisticsAction } from '../../../hooks/useLogisticsAction';
import { completeOrderStatus } from '../../../api/platformOrders/orders/list';
import { useFilterSearch } from '../../../hooks/useFilterSearch';
// 使用 Hook，传入刷新方法
const { execute } = useLogisticsAction(() => {
  customTableRef.value?.refresh();
});

// 拦截物流
const logisticsInterception = (row: any) => {
  execute(row, 'intercept');
};

// 取消发货
const cancelOrder = (row: any) => {
  execute(row, 'cancel');
};

// 删除订单
const delOrder = (row: any) => {
  execute(row, 'remove');
};

const customStore = useCustomStore();
const isSearchCollapsed = ref(false);
// table
const customTableRef = ref();
// 筛选
const filterTableRef = ref();
// 跟进详情
const customerFollowUpRef = ref();
// 批量下发
const batchAllocationRef = ref();
// 用户下单记录
const customerOrderHistoryRef = ref();
// 创建复购单
const addPorderRef = ref();
// 创建多包裹订单
const createMultiPackageOrderRef = ref();
// 创建退货单
const returnOrderDialogRef = ref();
// 创建补货单
const replenishOrderDialogRef = ref();
// 修改代付弹窗
const modifyPaymentDialogRef = ref();
// 批量打印
const batchPrintDialogRef = ref();
// 单张打印
const singlePrintDialogRef = ref();
// 统一管理search
const { filterChange, onSubmit } = useFilterSearch(customTableRef);

// 字典集合
const {
  sys_logistics_company: logisticsCompany, // 物流公司
  sys_pay_type: payType, // 支付类型
  sys_goods_type: goodsTypes, // 商品类型
  sys_order_type: orderTypeOptions, // 订单类型
  sys_replenish_order: replenishTypeOptions, // 订单类型
  sys_sales_return: returnTypeOptions, // 退货类型
  sys_order_from: orderFrom, // 订单来源
  sys_self_fulfillment_ogistics: sysSelfFulfillmentOgistics, // 第三方快递
  sys_logistics_type: logisticsTypeOptions // 物流类型
} = useDict(
  'sys_logistics_company',
  'sys_pay_type',
  'sys_goods_type',
  'sys_order_type',
  'sys_replenish_order',
  'sys_sales_return',
  'sys_order_from',
  'sys_self_fulfillment_ogistics',
  'sys_logistics_type'
);

/** 下发人可根据实际数据替换 */
const { ywList: users } = useYw();
// 基础商品列表
const { goodsList } = useGoods();

// 选中项
const selections = ref<any>([]);
const onSelectionChange = (selection: any[]) => {
  selections.value = selection;
};

// 批量分配
const onAllocation = (row?: any) => {
  const rows = cloneDeep(row ? [row] : selections.value);
  if (isEmpty(rows)) {
    ElMessage.warning('请先选择订单');
    return;
  }
  const deePpackages = rows.filter((v: any) => {
    return !v.isChildren;
  });
  batchAllocationRef.value?.show(deePpackages);
};

// 批量打印
const onBatchPrint = () => {
  const packages = cloneDeep(selections.value);
  // 过滤出主订单 和 待发货订单
  const deePpackages = packages.filter((v: any) => {
    return !v.isChildren && v.orderStatus === 140;
  });

  if (deePpackages.length) {
    batchPrintDialogRef.value?.show(deePpackages);
  } else {
    ElMessage.warning('当前页暂无有效待发货订单');
  }
};

// 单张打印
const onSinglePrint = (row: any) => {
  singlePrintDialogRef.value?.show(cloneDeep(row));
};

// 查看订单记录
const payHistory = (row: any) => {
  // customerId
  customerOrderHistoryRef.value?.show(row);
};

// 创建/追加复购单
// type === 'add'
// data 如果有值则为指定追加,不需要选择
const onAdd = (type: string, data?: any) => {
  addPorderRef.value?.show(type, data);
};

// 创建多包裹复购单
const onMultiPackage = () => {
  createMultiPackageOrderRef.value?.show();
};

// 新增退货单
const onReturnOrder = (row?: any) => {
  returnOrderDialogRef.value?.show(row);
};

// 新增补发单/追加复购单
const onReplenishOrder = (row?: any) => {
  replenishOrderDialogRef.value?.show(row);
};

// 编辑普通复购单
const onEdit = (type: any, data: any) => {
  addPorderRef.value.show(type, data);
};

// 编辑多包裹复购单
const onEditMulti = (data: any, type: any) => {
  createMultiPackageOrderRef.value.show(data, type);
};

// 处理下拉菜单点击
const handleCommand = (command: any, row: any) => {
  const data = cloneDeep(row);
  switch (command) {
    case 'edit':
      // 判断是多包裹 还是 普通复购单
      if (data.isMultiPackage) {
        onEditMulti('edit', data);
      } else {
        onEdit('edit', data);
      }
      break;
    // 分配业务员逻辑
    case 'allocation':
      onAllocation(data);
      break;
    // 取消发货
    case 'cancel':
      cancelOrder(data);
      break;
    // 拦截逻辑(取消物流)
    case 'intercept':
      logisticsInterception(data);
      break;
    // 删除订单
    case 'del':
      delOrder(data);
      break;
    case 'return':
      onReturnOrder(data);
      break;
    case 'replenish':
      onReplenishOrder(data);
      break;
    case 'modifyPayment':
      modifyPaymentDialogRef.value.show(data);
      break;
    case 'print':
      onSinglePrint(data);
      break;
    case 'complete':
      completeOrder(data);
      break;
    default:
      break;
  }
};

// 订单完成 二次确认
const completeOrder = (row: any) => {
  ElMessageBox.confirm('确认订单已完成/已签收？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    completeOrderStatus({
      orderId: row.orderId
    }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success('订单完成');
        customTableRef.value?.search();
      }
    });
  });
};

onMounted(() => {
  // 初始化类别数据
  customStore.initCustom();
});
</script>

<style scoped lang="scss">
.container {
  padding: 16px;

  .productName {
    font-weight: bold;
  }

  .alertFpBtn {
    padding-left: 0;
    padding-right: 0;
  }

  .payCount {
    cursor: pointer;
  }

  .remarkBox {
    .newReamark {
      display: block;
      text-wrap: wrap;
      text-align: left;
      line-height: 18px;
      font-size: 13px;
      margin-bottom: 5px;
    }
  }
}
</style>
